package com.xbongbong.formula.qlexpress.operator.date;

import com.ql.util.express.Operator;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.PaasDateUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/8/9 9:51
 * @since v1.0
 */
public class OperatorAddYear extends Operator {


    public OperatorAddYear(String name){
        this.name = name;
    }

    public OperatorAddYear(String aliasName, String aName, String errorInfo){
        this.aliasName = aliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }

    /**
     * 语法：ADDYEAR(date,years)
     * 说明：将指定日期加/减指定年数，date为指定日期，years为指定年数，当为负数时在此date上减去此年数
     * 例如：录入【合同开始时间】、【合同有效年限】，通过ADDYEAR函数自动填入【合同到期时间】。
     * @param list
     * list[0] 指定日期
     * list[1] 指定年数
     */
    @Override
    public Object executeInner(Object[] list) throws XbbException {
        if (Objects.isNull(list) || list.length < Constant.LENGTH) {
            return null;
        }
        Boolean isNumber = RegexUtil.isInteger(list[1].toString());
        if (!isNumber) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261007);
        }
        if (list[0] == null || StringUtils.equals(list[0].toString(), Constant.ZERO_STRING)) {
            return null;
        }
        // 指定年数
        Integer intervalYear = Integer.valueOf(list[1].toString());
        Long startTime = PaasDateUtil.getInt(list[0]);
        return DateTimeUtil.getIntByIntervalYear(startTime, intervalYear);
    }

}
